What is koa-session?
koa-session is a session middleware for Koa, a popular web framework for Node.js. It provides a way to manage user sessions, including storing session data, setting session cookies, and handling session expiration.
What are koa-session's main functionalities?
Basic Session Setup
This code sets up a basic Koa application with session management. It configures the session middleware with various options like cookie key, max age, and httpOnly flag. The middleware is then used to track the number of views for each session.
const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'koa:sess', // cookie key (default is koa:sess)
maxAge: 86400000, // cookie's max age in ms (1 day)
autoCommit: true, // automatically commit headers (default true)
overwrite: true, // can overwrite or not (default true)
httpOnly: true, // httpOnly or not (default true)
signed: true, // signed or not (default true)
rolling: false, // Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown.
renew: false, // renew session when session is nearly expired, so we can always keep user logged in.
};
app.use(session(CONFIG, app));
app.use(ctx => {
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
Custom Session Store
This code demonstrates how to use a custom session store with koa-session. The custom store is implemented using a simple in-memory Map. The store object provides methods for getting, setting, and destroying session data.
const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();
app.keys = ['some secret hurr'];
const store = {
storage: new Map(),
get(key) {
return this.storage.get(key);
},
set(key, sess) {
this.storage.set(key, sess);
},
destroy(key) {
this.storage.delete(key);
}
};
const CONFIG = {
store,
};
app.use(session(CONFIG, app));
app.use(ctx => {
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
Session Regeneration
This code shows how to regenerate a session in koa-session. When the user accesses the '/regenerate' path, the session is regenerated, which can be useful for security purposes, such as after a user logs in.
const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {};
app.use(session(CONFIG, app));
app.use(async ctx => {
if (ctx.path === '/favicon.ico') return;
if (ctx.path === '/regenerate') {
await ctx.regenerateSession();
ctx.body = 'Session regenerated';
} else {
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
}
});
app.listen(3000);
Other packages similar to koa-session
express-session
express-session is a session middleware for Express, another popular web framework for Node.js. It provides similar functionalities to koa-session, such as session storage, cookie management, and session expiration. However, it is designed to work with Express rather than Koa.
cookie-session
cookie-session is a lightweight session middleware that stores session data in cookies rather than on the server. This can be useful for small session data and simplifies the setup by not requiring a session store. It works with both Koa and Express.
koa-generic-session
koa-generic-session is another session middleware for Koa. It provides more flexibility and customization options compared to koa-session, such as support for different session stores and more advanced session management features.
koa-session
Simple session middleware for Koa. Defaults to cookie-based sessions and supports external stores.
Requires Node 8.0.0 or greater for async/await support
Installation
$ npm install koa-session
Notice
6.x changed the default cookie key from koa:sess
to koa.sess
to ensure set-cookie
value valid with HTTP spec.see issue. If you want to be compatible with the previous version, you can manually set config.key
to koa:sess
.
Example
View counter example:
const session = require('koa-session');
const Koa = require('koa');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'koa.sess',
maxAge: 86400000,
autoCommit: true,
overwrite: true,
httpOnly: true,
signed: true,
rolling: false,
renew: false,
secure: true,
sameSite: null,
};
app.use(session(CONFIG, app));
app.use(ctx => {
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
console.log('listening on port 3000');
API
Options
The cookie name is controlled by the key
option, which defaults
to "koa.sess". All other options are passed to ctx.cookies.get()
and
ctx.cookies.set()
allowing you to control security, domain, path,
and signing among other settings.
Custom encode/decode
Support
Use options.encode
and options.decode
to customize your own encode/decode methods.
Hooks
valid()
: valid session value before use itbeforeSave()
: hook before save session
External Session Stores
The session is stored in a cookie by default, but it has some disadvantages:
You can store the session content in external stores (Redis, MongoDB or other DBs) by passing options.store
with three methods (these need to be async functions):
get(key, maxAge, { rolling, ctx })
: get session object by keyset(key, sess, maxAge, { rolling, changed, ctx })
: set session object for key, with a maxAge
(in ms)destroy(key, {ctx})
: destroy session for key
Once you pass options.store
, session storage is dependent on your external store -- you can't access the session if your external store is down. Use external session stores only if necessary, avoid using session as a cache, keep the session lean, and store it in a cookie if possible!
The way of generating external session id is controlled by the options.genid(ctx)
, which defaults to uuid.v4()
.
If you want to add prefix for all external session id, you can use options.prefix
, it will not work if options.genid(ctx)
present.
If your session store requires data or utilities from context, opts.ContextStore
is also supported. ContextStore
must be a class which claims three instance methods demonstrated above. new ContextStore(ctx)
will be executed on every request.
Events
koa-session
will emit event on app
when session expired or invalid:
session:missed
: can't get session value from external store.session:invalid
: session value is invalid.session:expired
: session value is expired.
Custom External Key
External key is used the cookie by default, but you can use options.externalKey
to customize your own external key methods. options.externalKey
with two methods:
get(ctx)
: get the external keyset(ctx, value)
: set the external key
Session#isNew
Returns true if the session is new.
if (this.session.isNew) {
} else {
}
Session#maxAge
Get cookie's maxAge.
Session#maxAge=
Set cookie's maxAge.
Session#externalKey
Get session external key, only exist when external session store present.
Session#save()
Save this session no matter whether it is populated.
Session#manuallyCommit()
Session headers are auto committed by default. Use this if autoCommit
is set to false
.
Destroying a session
To destroy a session simply set it to null
:
this.session = null;
License
MIT